﻿@model X_Code.Benefit.Kafeteria.Web.Areas.Kafeteria.Models.KafeteriaModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Kafeteria/Views/Shared/Layout.cshtml";
}
@section head{
    <style type="text/css">
		@Html.Raw(ViewData["styles"] as string)
	</style>
    <style type="text/css">
        @foreach (var bground in Model.PlatformGraphicList)
        {
            @Html.Raw(".bg-img-" + bground.PlatformId + " { background:url(" + bground.TextureUrl + "); }");
        }
    </style>
    <link type="text/css" rel="Stylesheet" href="@Url.Content("~/Scripts/jqTools/css/overlay-apple.css")" />
    <script type="text/javascript" src="@Url.Content("~/Scripts/fancybox/jquery.mousewheel-3.0.4.pack.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/fancybox/jquery.fancybox-1.3.4.pack.js")"></script>
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/Scripts/fancybox/jquery.fancybox-1.3.4.css")" media="screen" />
    @*<link rel="stylesheet" type="text/css" href="@Url.Content("~/Scripts/fancybox/jquery.fancybox-1.3.4.css")" media="top-menuscreen" />*@
    <script type="text/javascript" language="javascript">

     var testvar = false;
     var inputId;
     var changeGorneLimity = true;
     var pId = '@TempData["_PlatformId"]';
		$(document).ready(function () {      

            $("#okbtnedsf").live("click", function () {
              var patt = new RegExp("^[0-9]+(\,[0-9]{1,2})?$");
              //var sp = $("#SP").val().replace('.', ',');
              var so = $("#SO").val().replace('.', ',').replace(/\s+/, ""); 
              var zfss = $("#ZFSS").val().replace('.', ',').replace(/\s+/, "");
               var sum = $("#SumLimitsEDSF").val().replace('.', ',').replace(/\s+/, "");
                inputId = "platofrm_tender_" + $("#CtsfIdEDSF").val();
            if (so == "") {
                so = "0";
            }
            if (zfss == "") {
                zfss = "0";
            }

             $.post('/Kafeteria/' + lang + '/Home/IsSourceFinanceCorrect', { 'src1': zfss, 'src2': so, 'src3': 0, 'sum': sum }, function (data) {
                    if (data == 'False') {
                    var text = '@Html._("Suma limitów powinna być równa")' + " " + sum;// + " " + '@Html._("limitów")' + " " + $("#ZFSSName").val() + " i " + $("#SOName").val(); //'@Model.';
                        //SetInformationBox(1,text);
                        //alert(text);
                        unlockExcludingProducts($("input[id^='" + v + "']"));
                        $("#declareCustomError").html(text).show();
                        return;
                    }

//            var zffsSpan = ("#platform_tender_row_" + $("#CtsfIdEDSF").val()) + " td span.ptZFSS";
//            var soSpan = ("#platform_tender_row_" + $("#CtsfIdEDSF").val()) + " td span.ptSO";
//            var spSpan = ("#platform_tender_row_" + $("#CtsfIdEDSF").val()) + " td span.ptSP";
                             // $('#platform_tender_row_15 td span.ptZFSS')          ptSP

             $.post('/Kafeteria/' + lang + '/Home/RoundLimit', { 'num': zfss.replace(',','.')},function(data){
                zfss = data;
             });
             $.post('/Kafeteria/' + lang + '/Home/RoundLimit', { 'num': so.replace(',','.')},function(data){
                so = data;
             });

            $("#platform_tender_row_" + $("#CtsfIdEDSF").val() + "* td span.ptZFSS").html(zfss);
            $("#platform_tender_row_" + $("#CtsfIdEDSF").val() + "* td span.ptSO").html(so);
            $("#platform_tender_row_" + $("#CtsfIdEDSF").val() + "* td span.ptSP").html('0,00');     
            
            $.post('/Kafeteria/' + lang + '/Home/SaveCustomSourceFinance', { 'zfss': zfss, 'so': so, 'sp': 0, 'ctsfId': $("#CtsfIdEDSF").val(), 'platformId': currentPlatformId }, function (data) {
            if(data != "True"){
                alert('@Html._("Bład przy zmianie źródeł finansowania")');
                 var v = ("platofrm_tender_" + $("#CtsfIdEDSF").val());
                 $("input[id^='" + v + "']").attr('checked', false);  

                 unlockExcludingProducts($("input[id^='" + v + "']"));
                 $.fancybox.close();
                 

            }           
            testvar = true;      
            przeliczLimity();

//            var curZFSS = parseFloat($("#ZFSSLimit").text());
//            var curSO = parseFloat($("#SOLimit").text());
//            var curSP = parseFloat($("#SPLimit").text()); 
//            
//            if(curZFSS < 0 || curSO < 0 || curSP < 0)
//            {            
//                SetInformationBox(1, '@Html._("Masz za mało dostępnych limitow")');                
//                $("#" + inputId).attr('checked', false);                   
//                przeliczLimity();
//            } 

            //$.fancybox.close();
            });
                    
           
                 
            $.fancybox.close();
            
             });

             

            });
             
             $("#cancelbtnedsf").live('click',function(){ 
                var v = ("platofrm_tender_" + $("#CtsfIdEDSF").val());               
                $("input[id^='" + v + "']").attr('checked', false);    
                przeliczLimity();                  
                $.fancybox.close();
                unlockExcludingProducts($("input[id^='" + v + "']"));
             });    
                           
            $('#content-historia-zamowien').css('position', 'absolute').css('top', '-10000px');
            $('#report-2').css('position', 'absolute').css('top', '-10000px');
            $.alerts.cancelButton = '@Html._("Anuluj")';

            var li_width = 0;

            $("#mainmenu ul li").each(function(){  
                li_width += $(this).outerWidth(true);
            });           

            if(li_width > 935)
            {
                $("#pod-top-2").removeClass(".pod-top-2").addClass(".pod-top-22");
                $("#kon-con").css('margin','0px auto');
                jQuery("#mycarousel").jcarousel({
                    scroll: 1,
                    itemFallbackDimension: 150
                });
            }
            else
            {
                $("#pod-top-2").removeClass(".pod-top-22").addClass(".pod-top-2");
                $("#top-con, #kon-con").css('margin','0px auto');
            }

            if(!isNaN(pId))
            {
                $("li[id^='tab-zamowienia']").trigger('click');
                $("a[id='tab-platform-" + pId + "']").trigger('click');
                ShowInformationBox();
            }
        });

		var platformGraphicList = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model.PlatformGraphicList));
        var ZFSSLimit, SOLimit, SPLimit, ZFSSLimitInUse, SOLimitInUse, SPLimitInUse, SPToPay;
        var BundlesLimit, BundlesLimitInUse;
        var maxKidAndKidsCount, orderedKidAndKidsCount;
        var currentPlatformId;
        var isNew;
        var showSessionDeclarationPopup;
        var CopyPasteInfo = '@Html._("Kopiuj/Wklej zostało zablokowane!")';
        var RightMouseClickInfo = '@Html._("Zablokowano prawy przycisk myszki!")';
        var SmsCodeNotMatch = '@Html._("Kod sms jest nieprawidłowy!")';
        var opt = '';

        function startSpinner(){ 
        //******************************************* 
                var asdf = document.body.clientHeight;                
                $("#loading").css('height',asdf + 'px');                
                $("#loading").fadeIn(); 
                var opts = { 
                lines: 12, // The number of lines to draw 
                length: 7, // The length of each line 
                width: 4, // The line thickness 
                radius: 10, // The radius of the inner circle 
                color: '#000', // #rgb or #rrggbb speed: 1, // Rounds per second 
                trail: 60, // Afterglow percentage 
                shadow: false, // Whether to render a shadow 
                hwaccel: false // Whether to use hardware acceleration 
            }; 
            $("#loading").html(''); 
            $("#loading").append(' <div id="loadingcontent"> <p id="loadingspinner">@Html._("Proszę czekać")</p></div>'); 
            var target = document.getElementById('loading'); 
            var spinner = new Spinner(opts).spin(target); 
                //*******************************************        
        } 
        function stopSpinner(){ 
        $("#loading").fadeOut(); 
        }

        function blockExcludingProducts(thisInput)
        {
            //blokowanie produktów wykluczających się
            var productGroupDiv = thisInput.closest("div.productGroup");
            if($(productGroupDiv).find('.isExcludeGroup').val() == "True")
            {
                productGroupDiv.find("input[id^='platofrm_tender_']").each(function(i,j){
                    if(thisInput.attr('id') != $(j).attr('id'))
                    {
                        $(j).removeAttr("checked");
                        $(j).attr("disabled","disabled");
                    }
                });
            }
        }

        function unlockExcludingProducts(thisInput)
        {
            //blokowanie produktów wykluczających się
            var productGroupDiv = thisInput.closest("div.productGroup");
            if($(productGroupDiv).find('.isExcludeGroup').val() == "True")
            {
                productGroupDiv.find("input[id^='platofrm_tender_']").each(function(i,j){
                    if(thisInput.attr('id') != $(j).attr('id'))
                    {
                        $(j).removeAttr("disabled");
                    }
                });
            }
        }

		$(function () {
            
            if(platformGraphicList != null)
            {
                for(var i = 0; i < platformGraphicList.length; i++)
                {
                    $("#preloadImages").append("<img src='" + platformGraphicList[i].TextureUrl + "'/>");
                }
            }
            
            showSessionDeclarationPopup = '@Model.ShowSessionDeclarationPopup'.toString().toLowerCase();

            //$.post('@Url.Action("PlatformTendersEagerLoad")', {}, function(){});

			/*****start: obsługa menu*****/
			$("li[id^='tab-']").click(function () {
				$(".tab-container").hide();
				var tabName = $(this).attr('id').substring(4);
                if (tabName == 'historia-zamowien') {
                    $('#content-historia-zamowien').css('position', 'relative').css('top', '0px');
                }
                else {
                    $('#content-historia-zamowien').css('position', 'absolute').css('top', '-10000px');
                }
                if(tabName == 'platnosci')
                {
                    $('#content-platnosci').load('@Url.Action("Payments", new { @Model.PaymentShortDescription })', function(){
                        var panelGraphic = getPlatformGraphic(currentPlatformId);
                        ReloadPlatformGUI(panelGraphic);
                    });
                    
                }
				$("#content-" + tabName).show();
				$("#mainmenu li").removeClass("active");
				$(this).addClass("active");
			});
			/*****koniec: obsługa menu*****/

            if('@Request.QueryString["opt"]' == 'checkChargeStatus')
            {
                opt = 'checkChargeStatus';
                $("li[id^='tab-zamowienia']").trigger('click');

                $.post('@Url.Action("PaymentStatusInfo")', null, function(data){ 
                    $(".platformContainer").html(data);

                    if(!isNaN('@TempData["chargePlatformId"]') && '@TempData["chargePlatformId"]' != '')
                    {
                        currentPlatformId = '@TempData["chargePlatformId"]';

				        $("#menu-platforms li").removeClass("active").removeClass("ui-tabs-selected").removeClass("ui-state-active");
                        $("#tab-platform-"+currentPlatformId).parent().addClass('active ui-tabs-selected ui-state-active');
                        $('div[id^="platforma-"]').addClass("ui-tabs-hide");
                        $("#platforma-"+currentPlatformId).removeClass("ui-tabs-hide");
                    }

                    var panelGraphic = getPlatformGraphic(currentPlatformId);
                    ReloadPlatformGUI(panelGraphic);
                });
            }

            $('#paymentListRefresh').live('click',function(){
                startSpinner();
                $.post('@Url.Action("Payments", new { @Model.PaymentShortDescription })', null, function(data){
                    $('#content-platnosci').html(data);
                    var panelGraphic = getPlatformGraphic(currentPlatformId);
                    ReloadPlatformGUI(panelGraphic);
                    stopSpinner();
                });
            });

            /*****start: obsługa przycisków zobacz*****/
			$("button[id^='see-']").click(function () {
				$(".tab-container").hide();
				var tabName = $(this).attr('id').substring(4);
				$("#content-" + tabName).show();
                if (tabName == 'historia-zamowien') {
                    $('#content-historia-zamowien').css('position', 'relative').css('top', '0px');
                }
                else {
                    $('#content-historia-zamowien').css('position', 'absolute').css('top', '-10000px');
                }
				$("#mainmenu li").removeClass("active");
                $("li#tab-"+tabName).addClass("active");
			});
			/*****koniec: obsługa przycisków zobacz*****/

            /*****start: obsługa przycisków zobacz*****/
			$("a[id^='see-link-']").click(function () {
				$(".tab-container").hide();
				var tabName = $(this).attr('id').substring(9);
				$("#content-" + tabName).show();
                if (tabName == 'historia-zamowien') {
                    $('#content-historia-zamowien').css('position', 'relative').css('top', '0px');
                }
                else {
                    $('#content-historia-zamowien').css('position', 'absolute').css('top', '-10000px');
                }
				$("#mainmenu li").removeClass("active");
                $("li#tab-"+tabName).addClass("active");
			});
			/*****koniec: obsługa przycisków zobacz*****/

            $("a[id^='tab-report-']").click(function(){
            
                var id = $(this).attr('id').substring(11);
                $('#report-2').css('position', 'relative').css('top', '0px');
                if(id=="1")
                    {
                    $("#tab-report-2").parent().removeClass("ui-tabs-selected");
                    $("#tab-report-1").parent().addClass("ui-tabs-selected");

                    $("#report-1").show();
                    $("#report-2").hide();

                    }
                    else
                    {
                    
                    $("#tab-report-1").parent().removeClass("ui-tabs-selected");
                    $("#tab-report-2").parent().addClass("ui-tabs-selected");                 

                    $("#report-2").show();
                    $("#report-1").hide();                    
                    }                       
                
            });

            if ($("#ShowLimits").val() == 'False' && $("#ShowBundles").val() == 'True')
                $("a[id^='tab-report-2']").trigger('click');

			/*****start: zmiana styli po wyborze innej platformy*****/
			$("a[id^='tab-platform-']").click(function(){                
				var panelGraphic = getPlatformGraphic($(this).attr('id').substring(13));
                //$(".bg-img").css("background-image","url('" + panelGraphic.TextureUrl + "')");
                currentPlatformId = $(this).attr('id').substring(13);

				$("#platformmenu li").removeClass("active");
				$(this).parent().addClass('active');

                var pId = $(this).attr('id').substring(13);
//                var asdf = document.body.clientHeight;                 
//                $("#loading").css('height',asdf + 'px');                 
//                $("#loading").fadeIn();
//                var opts = {
//                lines: 12, // The number of lines to draw
//                length: 7, // The length of each line
//                width: 4, // The line thickness
//                radius: 10, // The radius of the inner circle
//                color: '#000', // #rgb or #rrggbb
//                speed: 1, // Rounds per second
//                trail: 60, // Afterglow percentage
//                shadow: false, // Whether to render a shadow
//                hwaccel: false // Whether to use hardware acceleration
//            };
//            $("#loading").html('');
//            $("#loading").append(' <div id="loadingcontent"> <p id="loadingspinner">Proszę czekać</p></div>');
//            var target = document.getElementById('loading');
//            var spinner = new Spinner(opts).spin(target);
                $.post("/Kafeteria/" + lang + "/Home/CanOrderNow", { platformId: currentPlatformId }, function(data){
                    var url;
                    if(data.toString().toLowerCase() == 'true')
                    {
                        url = "/Kafeteria/" + lang +"/Home/PlatformNewOrder";
                        getSubTabContent(url, pId, true);                        
                    }
                    else
                    {
                        url = "/Kafeteria/" + lang +"/Home/PlatformLastOrder";
                        getSubTabContent(url, pId, false, true);
                    }
                    
                    refreshInfo();
                });
			});
			/*****koniec: zmiana styli po wyborze innej platformy*****/
            
            $("#change-frequency-cancel").live('click',function(){
                $.fancybox.close();
                du = false;
            });

            $("#change-frequency-save").live('click',function(){
                var freq = $("#Frequency").val();

                $.post('@Url.Action("SaveNewFrequency", "Home")', { frequency: freq, platformId: currentPlatformId }, function(){
                    $.fancybox.close();
                    showSessionDeclarationPopup = false;
                    $("a[id='tab-platform-" + currentPlatformId + "']").trigger('click');
                });
            });

			$("a[id^='tab-platform-']:eq(0)").trigger('click');
			$("#taby-top").tabs();
			$("#taby-top2").tabs();

//			$("a[rel]").overlay({
//				top: 260,
//                mask: {
//                    color: '#ccc',
//                    loadSpeed: 200,
//                    opacity: 0.5
//                },
//                closeOnClick: false,
//                load: false
//			});

            /*****start: obsługa zamówienia*****/
            
            $("input[id^='platofrm_tender_']").live('change',function(){
                var ptNo = $(this).attr('id').substring(16);
                        
                startSpinner();
                var thisInput = $(this);

                var _zfss = $("tr[id='platform_tender_row_" + ptNo + "'] .ptZFSS").text();
                var _so = $("tr[id='platform_tender_row_" + ptNo + "'] .ptSO").text();
                var _sp = $("tr[id='platform_tender_row_" + ptNo + "'] .ptSP").text();
                var _quantity = $("tr[id='platform_tender_row_" + ptNo + "'] .quantity").val();
                var _employeeDeclareSourceFinance = $("#can_employee_declare_source_finance_" + ptNo).val() == "True";
                var  edsfLink2 = '@Url.Action("EmployeeDeclareSourceFinance")' + '/' + ptNo + '?platformId=' +currentPlatformId;

//            $("a.employee-declare-source-finance").attr('href',edsfLink2);
//            $("a.employee-declare-source-finance").trigger('click'); 
                                                      
                if($(this).is(':checked') == true)
                {
                    ////START - sprawdzenie czy może zamówić wybrany produkt (w danej ilości)
                    var ctsfId = $(this).closest('tr[id^="platform_tender_row_"]').find("input[id^='ctsf_']").attr("id").substring(5);
                
                    var tenders = "ctsfId=" + ctsfId + "&quantity=" + _quantity + "&platformId=" + currentPlatformId;
                    var counter = 0;
                    $("input[id^='platofrm_tender_']:checked").each(function () {
                        //tenders += "&productOrders[" + counter + "].PlatformTenderId=" + $(this).attr('id').substring(16);
                        tenders += "&productOrders[" + counter + "].Quantity=" + $(this).closest('tr').find('.quantity').val();
                        tenders += "&productOrders[" + counter + "].CustomerTenderSourceFinanceId=" + $(this).closest('tr').find("input[id^='ctsf_']").val();

                        var holderCounter = 0;

                        $(this).closest('tr').find('.holderName').each(function(){
                            tenders += "&productOrders[" + counter +"].HolderList[" + holderCounter + "].Name=" + $(this).val();
                            tenders += "&productOrders[" + counter +"].HolderList[" + holderCounter + "].Surname=" + $(this).closest('tr').find('.holderSurname').val();
                            holderCounter = holderCounter + 1;
                        });
                                        
                        counter = counter + 1;
                    });

                    if(!isNew)
                    {
                        tenders += "&isValidateToShow=false&isActualization=true&epActual=null";
                    }
                    else
                    {
                        tenders += "&isValidateToShow=false&isActualization=false&epActual=null";
                    }

                    $.post('@Url.Action("CanOrderTender", "Home")', tenders, function(data){
                        if(data != 'OK')
                        {
                            stopSpinner();
                            thisInput.removeAttr('checked');

                            if (data != 'NoPhoneDefined'){
                                SetInformationBox(1, getMessage(data));
                            }
                            else{
                                popupChangePhone(getMessage(data));
                            }
                        }
                        else
                        {
                                if(((parseFloat(ZFSSLimit) < (ZFSSLimitInUse + parseFloat(_zfss)*_quantity)) || (parseFloat(SOLimit) < (SOLimitInUse + parseFloat(_so)*_quantity)) || ((parseFloat(SPLimit) < (SPLimitInUse + parseFloat(_sp)*_quantity) && $("#CanPay").val() == "False"))) && !_employeeDeclareSourceFinance)
                                {
                                   
                                    SetInformationBox(1, '@Html._("Masz za mało dostępnych limitow")');
                                    thisInput.removeAttr('checked');
                                    thisInput.closest('tr').find('.quantity').val('1');
                                    thisInput.closest('tr').find('.quantity').trigger('keyup');
                                }
                                else
                                {
                                    if(thisInput.closest('td').find('.isMultiDeal').val() == 'True' && thisInput.closest('td').find('.allowResignationMD').val() == 'False')
                                    {
                                        var confirmationText = '@Html._("Uwaga. Nie będzie możliwości z rezygnacji z tego produktu. Czy kontynuować?")';
                                        
                                        jConfirm(confirmationText, '@Html._("Oświadczenie")', function(r) {
                                           if(!r){
                                           thisInput.removeAttr('checked');
                                           unlock(thisInput);
                                            stopSpinner();
                                            return;
                                           }
                                           var pronouncement = thisInput.closest('tr').find("input[id^='tender_pronouncement_']").val();

                                            if(pronouncement != undefined && pronouncement != "")
                                            {
                                                jConfirm(pronouncement, '@Html._("Oświadczenie")', function(r) {
                                                if(!r){
                                                   thisInput.removeAttr('checked');
                                                   unlockExcludingProducts(thisInput);
                                                   stopSpinner();
                                                    return;
                                                    }

                                                    if(parseFloat(_zfss) == 0 && parseFloat(_so) == 0 && parseFloat(_sp) > 0)
                                                    {
                                                        var testpron = !confirm('@Html._("Czy wyrażasz zgodę na obciążenie wartością świadczenia swojego miesięcznego wynagrodzenia?")');
                                                        if(testpron)
                                                        {
                                                            thisInput.removeAttr('checked');
                                                            unlockExcludingProducts(thisInput);
                                                            stopSpinner();
                                                            return;
                                                        }
                                                    }


                                                    blockExcludingProducts(thisInput);

                                                    if(_employeeDeclareSourceFinance || testpron){
                                                       //alert("test");   
                                                       // var  edsfLink = '@Url.Action("EmployeeDeclareSourceFinance")' + '/' + ptNo;
                                                       $("a.employee-declare-source-finance").attr('href',edsfLink2);
                                                       $("a.employee-declare-source-finance").trigger('click');                                               
                                                    }else{
                                                    przeliczLimity();
                                                    }
                                                });
                                            }  else{
                                                
                                             blockExcludingProducts(thisInput);

                                             if(parseFloat(_zfss) == 0 && parseFloat(_so) == 0 && parseFloat(_sp) > 0)
                                            {
                                                if(!confirm('@Html._("Czy wyrażasz zgodę na obciążenie wartością świadczenia swojego miesięcznego wynagrodzenia?")'))
                                                {
                                                    thisInput.removeAttr('checked');
                                                    unlockExcludingProducts(thisInput);
                                                    stopSpinner();
                                                    return;
                                                }
                                            }

                                             if(_employeeDeclareSourceFinance){
                                                    //alert("test");   
                                                    // var  edsfLink = '@Url.Action("EmployeeDeclareSourceFinance")' + '/' + ptNo;
                                                    $("a.employee-declare-source-finance").attr('href',edsfLink2);
                                                    $("a.employee-declare-source-finance").trigger('click');                                               
                                                }else{
                                            przeliczLimity();
                                        }
                                        }
                                        });
                                    }
                                    else
                                    {
                                        var pronouncement = thisInput.closest('tr').find("input[id^='tender_pronouncement_']").val();

                                        if(pronouncement != undefined && pronouncement != "")
                                        {
                                            jConfirm(pronouncement, '@Html._("Oświadczenie")', function(r) {
                                            if(!r){
                                               thisInput.removeAttr('checked');
                                               unlockExcludingProducts(thisInput);
                                                stopSpinner();
                                                return;
                                                }

                                                blockExcludingProducts(thisInput);

                                                if(parseFloat(_zfss) == 0 && parseFloat(_so) == 0 && parseFloat(_sp) > 0)
                                                {
                                                    if(!confirm('@Html._("Czy wyrażasz zgodę na obciążenie wartością świadczenia swojego miesięcznego wynagrodzenia?")'))
                                                    {
                                                        thisInput.removeAttr('checked');
                                                        unlockExcludingProducts(thisInput);
                                                        stopSpinner();
                                                        return;
                                                    }
                                                }

                                                  if(_employeeDeclareSourceFinance){
                                                       //alert("test");   
                                                       // var  edsfLink = '@Url.Action("EmployeeDeclareSourceFinance")' + '/' + ptNo;
                                                       $("a.employee-declare-source-finance").attr('href',edsfLink2);
                                                       $("a.employee-declare-source-finance").trigger('click');                                               
                                                    } else{

                                                przeliczLimity();
                                                    }
                                            });
                                        }else{

                                        blockExcludingProducts(thisInput);

                                        if(parseFloat(_zfss) == 0 && parseFloat(_so) == 0 && parseFloat(_sp) > 0)
                                        {
                                            if(!confirm('@Html._("Czy wyrażasz zgodę na obciążenie wartością świadczenia swojego miesięcznego wynagrodzenia?")'))
                                            {
                                                thisInput.removeAttr('checked');
                                                unlockExcludingProducts(thisInput);
                                                stopSpinner();
                                                return;
                                            }
                                        }

                                         if(_employeeDeclareSourceFinance){
                                                       //alert("test");   
                                                       // var  edsfLink = '@Url.Action("EmployeeDeclareSourceFinance")' + '/' + ptNo;
                                                       $("a.employee-declare-source-finance").attr('href',edsfLink2);
                                                       $("a.employee-declare-source-finance").trigger('click');                                               
                                                    } else{
                                        przeliczLimity();
                                        }
                                    }
                                }
                                }

                        }

                        stopSpinner();
                    });
                    ////KONIEC - sprawdzenie czy może zamówić wybrany produkt (w danej ilości)
                }
                else
                {
                    if(!isNew && $("input[id^='platofrm_tender_']:checked").length == 0)
                    {
                        thisInput.attr("checked","checked");
                        SetInformationBox(1,'@Html._("Nie możesz odznaczyć wszystkich produktów. Przynajmniej jeden musi być zaznaczony.")');
                    }
                    else
                    {
                        if($(this).closest("td").find(".employeeOrVIP").val().toLowerCase() == 'true')
                        {
                            if($("#OtherCardsWithEmployeeOrVIPCard").val().toLowerCase() == 'true') //jeśli karty typu kid, kids ,osTow mozna zamawiac jedynie z karta pracownik lub vip
                            {
                                stopSpinner();
                                SetInformationBox(1, '@Html._("Odznaczyłeś/-aś zamówienie karty typu 'Pracownik' lub 'VIP'. Ponieważ ustawienia nie pozawalają na zamawianie pozostałych typów kart bez karty 'Pracownik' lub 'VIP', zamówienia takie zostaną odznaczone.")');
                                    $(".isMultisportCard").each(function(index,element){
                                        if($(element).val().toString().toLowerCase() == 'true')
                                        {
                                            $(element).closest("td").find("input[id^='platofrm_tender_']").removeAttr("checked");
                                        }
                                    });
                            }
                        }

                        if(isNew) //Jeśli jest to edycja nie odszarzaj checkboxów
                        {
                            unlockExcludingProducts(thisInput);
                        }
                    }
                    
                    przeliczLimity();
                    stopSpinner();
                }
                //przeliczLimity();
            });

            $(".quantity").live('keyup',function(){
                if($("#IsDetailsMode").val().toLowerCase() != 'true')
                {
                    if ($('#Bundle').val() != 'True')
                    {
                        var ctsfId = $(this).closest('tr[id^="platform_tender_row_"]').find("input[id^='ctsf_']").attr("id").substring(5);
                
                        ////START - sprawdzenie czy może zamówić wybrany produkt (w danej ilości)
                        
                        var temp = parseInt($(this).val());

                        if(isNaN(temp)) {
                            $(this).val('1');
                            SetInformationBox(1,'@Html._("Niepoprawny format - Ilość musi być liczbą całkowitą większą od zera.")');
                            //ShowInformationBox();
                            return;
                        }

                        if (temp <= 0) {
                            $(this).val('1');
                            SetInformationBox(1,'@Html._("Ilość musi być większa od zera.")');
                            //ShowInformationBox();
                            return;
                        }
                        

                            var tenders = "ctsfId=" + ctsfId + "&quantity=" + $(this).val() + "&platformId=" + currentPlatformId;
                            var counter = 0;
                            $("input[id^='platofrm_tender_']:checked").each(function () {
                                tenders += "&productOrders[" + counter + "].PlatformTenderId=" + $(this).attr('id').substring(16);
                                tenders += "&productOrders[" + counter + "].Quantity=" + $(this).closest('tr').find('.quantity').val();
                                tenders += "&productOrders[" + counter + "].CustomerTenderSourceFinanceId=" + $(this).closest('tr').find("input[id^='ctsf_']").val();

                                var holderCounter = 0;SetInformationBox

                                $(this).closest('tr').find('.holderName').each(function(){
                                    tenders += "&productOrders[" + counter +"].HolderList[" + holderCounter + "].Name=" + $(this).val();
                                    tenders += "&productOrders[" + counter +"].HolderList[" + holderCounter + "].Surname=" + $(this).closest('tr').find('.holderSurname').val();
                                    holderCounter = holderCounter + 1;
                                });
                                        
                                counter = counter + 1;
                            });

                            var thisInput = $(this);
                            if(!isNew)
                            {
                                tenders += "&isValidateToShow=false&isActualization=true&epActual=null";
                            }
                            else
                            {
                                tenders += "&isValidateToShow=false&isActualization=false&epActual=null";
                            }

                            startSpinner();
                            $.post('@Url.Action("CanOrderTender", "Home")', tenders, function(data){
                                if(data != 'OK')
                                {
                                    thisInput.closest('tr[id^="platform_tender_row_"]').find('input[id^="platofrm_tender_"]').removeAttr('checked');
                            
                                    if (data != 'NoPhoneDefined'){
                                        SetInformationBox(1, getMessage(data));
                                    }
                                    else{
                                        popupChangePhone(getMessage(data));
                                    }
                                }
                   
                                var value = thisInput.val();
                
                                var holderNameTBox = '<table><tr><td style="margin: 0px 2px 0px 0px; padding: 0px;" ><input type="text" style="width: 90%; margin-bottom: 2px;" class="holderName" /></td><td style="margin: 0px; padding: 0px;"><input type="text" style="width: 90%; margin-bottom: 2px;" class="holderSurname" /></td></tr></table>';
                                                
                                var holderNamesTBs = '';
                                

                                if(thisInput.closest('tr[id^="platform_tender_row_"]').find("input[id^='personal_']").val().toString().toLowerCase() == 'true')
                                {
                                    if(isNaN(value))
                                    {
                                        val = 1;
                                        $(this).val(val);
                                        holderNamesTBs = holderNameTBox;
                                    }
                                    else
                                    {
                                        var tbsCount = thisInput.closest('tr[id^="platform_tender_row_"]').find(".holderName").length;
                        
                                        if(tbsCount < parseFloat(value))
                                        {
                                            for(var i = tbsCount; i < parseFloat(value); i++)
                                            {
                                                holderNamesTBs += holderNameTBox;
                                                if(i < value -1)
                                                {
                                                    holderNamesTBs += '<br/>';
                                                }
                                            }

                                            thisInput.closest('tr[id^="platform_tender_row_"]').find(".holderNameConatainer").append(holderNamesTBs);
                                        }
                        
                                        if(parseFloat(value) == 1)
                                        {
                                            thisInput.closest('tr[id^="platform_tender_row_"]').find(".holderNameConatainer").html(holderNameTBox);
                                        }
                                        else if(tbsCount > parseFloat(value))
                                        {
                                            thisInput.closest('tr[id^="platform_tender_row_"]').find(".holderName:last").closest('table').remove();
                                        }
                                    }
                                }
                                else
                                {
                                    holderNamesTBs = 'N / D';
                                    thisInput.closest('tr[id^="platform_tender_row_"]').find(".holderNameConatainer").html(holderNamesTBs);
                                }

                                var ptNo = thisInput.closest('tr[id^="platform_tender_row_"]').find("input[id^='platofrm_tender_']").attr('id').substring(16);
                
                                var _zfss = $("tr[id='platform_tender_row_" + ptNo + "'] .ptZFSS").text();
                                var _so = $("tr[id='platform_tender_row_" + ptNo + "'] .ptSO").text();
                                var _sp = $("tr[id='platform_tender_row_" + ptNo + "'] .ptSP").text();
                                var _quantity = $("tr[id='platform_tender_row_" + ptNo + "'] .quantity").val();

                                przeliczLimity(thisInput.attr('id'));
                                stopSpinner();                

                        });//koniec posta
                    }
                    else//zamawianie lub edycja pakietów ==> dodajemy pola do okazicieli bez przeliczania i sprawdzania warunków
                    {
                                var thisInput = $(this);
                                var value = thisInput.val();

                                var id = thisInput.attr('id').substring(16);
                                $("#bundle_products_" + id).find('tr[id^="platform_tender_row_"]').each(function(){
                                        var row = $(this);
                                        var holderNameTBox = '<table><tr><td style="margin: 0px 2px 0px 0px; padding: 0px;" ><input type="text" style="width: 90%; margin-bottom: 2px;;" class="holderName" /></td><td style="margin: 0px; padding: 0px;"><input type="text" style="width: 90%; margin-bottom: 2px;" class="holderSurname" /></td></tr></table>';
                                        var holderNamesTBs = '';
                                        if (row.find("input[id^='personal_']").val().toString().toLowerCase() == 'true')
                                        {
                                            if(isNaN(value))
                                            {
                                                val = 1;
                                                $(this).val(val);
                                                holderNamesTBs = holderNameTBox;
                                            }
                                            else
                                            {
                                                var rowQuantity = row.find(".quantity").val();
                                                var newQuantity = parseFloat(value) * parseFloat(rowQuantity);
                                                var tbsCount = row.find(".holderName").length;
                                                if(tbsCount < newQuantity)
                                                {
                                                    for(var i = tbsCount; i < (newQuantity); i++)
                                                    {
                                                        holderNamesTBs += holderNameTBox;
                                                        if(i < newQuantity -1)
                                                        {
                                                            //holderNamesTBs += '<br/>';
                                                        }
                                                    }

                                                    row.find(".holderNameConatainer").append(holderNamesTBs);
                                                }
                        
                                                if(tbsCount > newQuantity)
                                                {
                                                    for (var i=0; i<parseFloat(rowQuantity); i++)
                                                        row.find(".holderName:last").closest('table').remove();
                                                }
                                            }
                                        }
                                        else
                                        {
                                            holderNamesTBs = 'N / D';
                                            row.find(".holderNameConatainer").html(holderNamesTBs);
                                        }
                                });
                    }
                }
            });

            $("#cleanForm").live('click',function(){
                $(".quantity").each(function(){
                    $(this).val('1');
                });
                
                /* Czyszczenie nadmiarowych elementów ze strony */
                $('.holderNameConatainer').each(function(i,e){
                    $(e).children('gt(0)').remove();
                    $(e).find('td input').val('');
                });

                $('.holderNameConatainer:eq(2)').children(':gt(0)').remove()

                $("input[id^='platofrm_tender']").each(function(){
                    if($(this).attr('disabled') != 'disabled')
                    {
                        $(this).removeAttr('checked');
                    }

                });

                $("input[id^='tender_bundle_']").each(function(){
                    if($(this).attr('disabled') != 'disabled')
                    {
                        $(this).removeAttr('checked');
                    }
                });

                przeliczLimity();
            });

            $("#save_order_limits").live('click',function(){
                if($(this).attr('disabled') == 'disabled')
                    return;

                startSpinner();

                $(this).attr('disabled','disabled');

                var thisButton = $(this);
                
                var isValid = true;
                $("#HolderNameMessage").hide();
                $("#PronouncementMessage").hide();

                $("input[id^='platform_pronouncement_']").each(function(){
                    if($(this).attr('checked') != 'checked')
                    {
                        isValid = false;
                        $("#PronouncementMessage").show();
                        thisButton.removeAttr('disabled');
                        stopSpinner();
                        return;
                    }
                });

                $(".holderName").each(function(){
                    if($(this).val() == "")
                    {
                        if($(this).closest('tr[id^="platform_tender_row_"]').find("input[id^='platofrm_tender_']").attr('checked') == 'checked')
                        {
                            isValid = false;
                            $("#HolderNameMessage").show();
                            thisButton.removeAttr('disabled');
                            stopSpinner();
                            return;
                        }
                    }
                });

                $(".holderSurname").each(function(){
                    if($(this).val() == "")
                    {
                        if($(this).closest('tr[id^="platform_tender_row_"]').find("input[id^='platofrm_tender_']").attr('checked') == 'checked')
                        {
                            isValid = false;
                            $("#HolderNameMessage").show();
                            thisButton.removeAttr('disabled');
                            stopSpinner();
                            return;
                        }
                    }
                });

                if(isValid)
                {
                    var tenders = "";
                    var tenderParams = [];
                    var counter = 0;
                    $("input[id^='platofrm_tender_']:checked").each(function () {
                        //tenders += "&productOrders[" + counter + "].PlatformTenderId=" + $(this).attr('id').substring(16);
                        tenders += "&productOrders[" + counter + "].Quantity=" + $(this).closest('tr').find('.quantity').val();
                        tenders += "&productOrders[" + counter + "].CustomerTenderSourceFinanceId=" + $(this).closest('tr').find("input[id^='ctsf_']").val();
                        
                        var holderCounter = 0;

                        $(this).closest('tr').find('.holderName').each(function(){
                            tenders += "&productOrders[" + counter +"].HolderList[" + holderCounter + "].Name=" + $(this).val();
                            tenders += "&productOrders[" + counter +"].HolderList[" + holderCounter + "].Surname=" + $(this).closest('tr').find('.holderSurname').val();
                            holderCounter = holderCounter + 1;
                        });
                                        
                        counter = counter + 1;
                    });

                    tenders += "&platformId=" + currentPlatformId; //$("#taby-top li.active a[id^='tab-platform-']").attr('id').substring(13);
                    
                    var employeeOrderId = parseInt($("#EmployeeOrderId").val());
                    if(employeeOrderId > 0)
                    {
                        tenders += "&employeeOrderId=" + employeeOrderId;
                        if($("#IsEdit").val().toLowerCase() == 'true')
                        {
                            $.post('/Kafeteria/' + lang + '/Home/UpdateProductsLimits', tenders,function(){ 
                                stopSpinner();
                                ShowInformationBox();
                                $("a[id='tab-platform-" + currentPlatformId + "']").trigger('click');
                            });
                        }
                        else
                        {
                            var queryString = {};
                            tenders.replace(
                                new RegExp("([^?=&]+)(=([^&]*))?", "g"),
                                function($0, $1, $2, $3) { queryString[$1] = $3; }
                            );
                            post_to_url('/Kafeteria/' + lang + '/Home/UpdateOrderLimits', queryString, 'post');
//                            $.post('/Kafeteria/' + lang + '/Home/UpdateOrderLimits', tenders,function(){ 
//                                stopSpinner();
//                                ShowInformationBox();
//                                $("a[id='tab-platform-" + currentPlatformId + "']").trigger('click');
//                            });
                        }
                    }
                    else
                    {
                        var queryString = {};
                        tenders.replace(
                            new RegExp("([^?=&]+)(=([^&]*))?", "g"),
                            function($0, $1, $2, $3) { queryString[$1] = $3; }
                        );

                        post_to_url('/Kafeteria/' + lang + '/Home/SaveOrderLimits', queryString, 'post');
//                            $.post('/Kafeteria/' + lang + '/Home/SaveOrderLimits', tenders,function(){ 
//                                stopSpinner();
//                                ShowInformationBox();
//                                $("a[id^='tab-platform-" + currentPlatformId + "']").trigger('click');
//                                refreshInfo();
//                            });
                    }
                }
            });

            $("#show_edit_form").live('click',function(){
                var url = "/Kafeteria/" + lang +"/Home/PlatformLastOrder";
                getSubTabContent(url, currentPlatformId, false, false);
            });

            $("#back_to_preview").live('click',function(){
                var url = "/Kafeteria/" + lang +"/Home/PlatformLastOrder";
                getSubTabContent(url, currentPlatformId, false, true);
            })

            $(".incrementQuantity").live('click',function(){
                var max = $(this).closest('tr').find('.max_quantity').val();
                var actual = $(this).closest('tr').find('.quantity').val();

                var isPeriodicAndRequired = false;
                if($(this).closest("tr[id^='platform_tender_row_']").find('.is_periodic').val().toString().toLowerCase() == 'true' && $(this).closest('tr[id^="platform_tender_row_"]').find("input[id^='platofrm_tender_']").attr('disabled') == 'disabled')
                    isPeriodicAndRequired = true;

                if($(this).closest("tr[id^='platform_tender_row_']").find(".kidorkids").val().toLowerCase() == 'true')
                {
                    if(orderedKidAndKidsCount < maxKidAndKidsCount)
                    {
                        if(parseFloat(actual) + 1 <= parseFloat(max) && !isPeriodicAndRequired){
                            var newVal = parseFloat(actual) + 1;
                            $(this).closest('tr').find('.quantity').val(newVal);
                            $(this).closest('tr').find('.quantity').trigger('keyup');
                        }
                        orderedKidAndKidsCount = orderedKidAndKidsCount + 1;
                    }

                    /* #7450 */
                    if(parseFloat(actual) + 1 > parseFloat(max)){
                        var msg = '@Html._("Możesz zamówić maksymalnie")';
                        msg += ' ' + max + ' ';
                        msg += '@Html._("sztuk")';
                        msg += '.';
                        SetInformationBox(1, msg);
                    }
//                    else
//                    {
//                        SetInformationBox(1, 'Html._("Maksymalna ilość jednocześnie zamawianych kart KID i KIDS wynosi"): ' + maxKidAndKidsCount);
//                    }
                }
                else
                {
                    if(parseFloat(actual) + 1 <= parseFloat(max) && !isPeriodicAndRequired){
                        var newVal = parseFloat(actual) + 1;
                        $(this).closest('tr').find('.quantity').val(newVal);
                        $(this).closest('tr').find('.quantity').trigger('keyup');
                    }

                    /* #7450 */
                    if(parseFloat(actual) + 1 > parseFloat(max)){
                        var msg = '@Html._("Możesz zamówić maksymalnie")';
                        msg += ' ' + max + ' ';
                        msg += '@Html._("sztuk")';
                        msg += '.';
                        SetInformationBox(1, msg);
                    }
                }
            });

            $(".decrementQuantity").live('click',function(){
                var min = 1;
                var actual = $(this).closest('tr').find('.quantity').val(); 
                
                var isPeriodicAndRequired = false;
                if($(this).closest("tr[id^='platform_tender_row_']").find('.is_periodic').val().toString().toLowerCase() == 'true' && $(this).closest('tr[id^="platform_tender_row_"]').find("input[id^='platofrm_tender_']").attr('disabled') == 'disabled')
                    isPeriodicAndRequired = true;
                
                //Kur*** smsy
                if ($(this).closest("tr[id^='platform_tender_row_']").find('.IsSmsDisabled').val().toString().toLowerCase() == 'true')
                    isPeriodicAndRequired = true;

                if(!isNew && $(this).closest('tr[id^="platform_tender_row_"]').find('.isMultiDeal').val() == 'True' && $(this).closest('tr[id^="platform_tender_row_"]').find('.canResignMD').val() == 'False')
                {
                    var minquantity = $(this).closest('tr[id^="platform_tender_row_"]').find('.minQuantityMD').val();
                    if(parseInt(actual) <= parseInt(minquantity))
                    {
                        $(this).find('td').find('.quantity').attr('value',minquantity);
                        SetInformationBox(1, '@Html._("Nie możesz zmniejszyć ilości tego produktu MultiDeals poniżej: ")' + minquantity);
                        return;
                    }
                }

                if(parseFloat(actual) - 1 >= 1 && !isPeriodicAndRequired){
                    if($(this).closest("tr[id^='platform_tender_row_']").find(".kidorkids").val().toLowerCase() == 'true')
                    {
                        orderedKidAndKidsCount = orderedKidAndKidsCount - 1;
                    }

                    var newVal = parseFloat(actual) - 1;
                    $(this).closest('tr').find('.quantity').val(newVal);
                    $(this).closest('tr').find('.quantity').trigger('keyup');
                }
            });

            /*** pakiety ***/
            $("input[id^='tender_bundle_']").live('change', function(){
                var $tb_bundle = $(this).closest('.bundle-div').find('input[id^="bundle_quantity_"]');
                var quantity = $tb_bundle.val();
                var bundles = "";
                var counter = 0;

                $("input[id^='tender_bundle_']:checked").each(function () { 
                            bundles += '&bundleOrders[' + counter + '].TenderBundleId=' + $(this).attr('id').substring(14);
                            bundles += '&bundleOrders[' + counter + '].Quantity=' + $("input[id='bundle_quantity_" + $(this).attr('id').substring(14) + "']").val();
                            counter += 1;
                    });

                bundles += '&bundleId=' + $(this).attr('id').substring(14);
                bundles += '&quantity=' + $("input[id='bundle_quantity_" + $(this).attr('id').substring(14) + "']").val();
                bundles += '&platformId=' + currentPlatformId;

                 if(!isNew)
                    bundles += "&isActualization=true";
                else
                    bundles += "&isActualization=false";

                bundles += "&fromJS=true";
                bundles += '&operation=';
                bundles += $(this).is(":checked") == true ? 'checked,':'unchecked,';
                bundles += $("#IsEdit").val().toLowerCase() == 'false' ? 'new,' : 'update,';
                bundles += 'none';
                var thisInput2 = $(this);

                if($(this).is(":checked") == true)
                { 
                    if((BundlesLimitInUse + parseFloat(quantity)) <= BundlesLimit)
                    {
                        startSpinner();
                        $.post('@Url.Action("CanOrderBundle", "Home")', bundles, function(data)
                        {
                            stopSpinner();
                            if(data != 'OK')
                            {
                                thisInput2.removeAttr('checked');
                                if (data != 'NoPhoneDefined'){
                                    SetInformationBox(1, getMessage(data));
                                }
                                else{
                                    popupChangePhone(getMessage(data));
                                   } 
                                    if(data =='NoSmsAvail'){
                                        //BundlesLimit += quantity;
                                        BundlesLimitInUse -= quantity;
                                        $('#Bundles, #Bundles2').text(BundlesLimit);
                                        $('#BundlesInUse').text(BundlesLimitInUse);
                                        $tb_bundle.val('1');
                                    }
                            }
                            else
                            {
                                /* Oświadczenie dla pakietu */
                                var pronouncment = thisInput2.closest('tr').find(".bundle_pronouncment").val();

                                if(pronouncment != undefined && pronouncment != "")
                                {
                                       jConfirm(pronouncment, '', function(r) {
                                        if(!r){
                                           thisInput2.removeAttr('checked');
                                            return;
                                            }

                                            var count = $("#bundle_products_" + id + " .bundle_tender_pronouncment").length;
                                            var counter = 0;

                                            if(count == 0)
                                            {
                                                BundlesLimitInUse = BundlesLimitInUse + parseFloat(quantity);

                                                if($("#IsEdit").val().toLowerCase() == 'false')
                                                    $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                                                else
                                                {
                                                    BundlesLimit -= parseFloat(quantity);
                                                    $("#Bundles").text(BundlesLimit);
                                                }

                                                $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                                                $("#BundlesInUse").text(BundlesLimitInUse);
                                            }
                                            else
                                            {
                                                $("#bundle_products_" + id + " .bundle_tender_pronouncment").each(function(){
                                                    var tenderPronouncment = $(this).val();
                                                    if(tenderPronouncment != undefined && tenderPronouncment != "" && isAcceptedProductsPronouncments == true)
                                                    {
                                                        jConfirm(pronouncment, '', function(r) {
                                                            if(!r){
                                                                thisInput.removeAttr('checked');
                                                                isAcceptedProductsPronouncments = false;
                                                                return;
                                                            }
                                                            counter = counter + 1;

                                                            if(counter == count)
                                                            { 
                                                                if(!isAcceptedProductsPronouncments)
                                                                    return;
                        

                                                                BundlesLimitInUse = BundlesLimitInUse + parseFloat(quantity);

                                                                if($("#IsEdit").val().toLowerCase() == 'false')
                                                                    $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                                                                else
                                                                {
                                                                    BundlesLimit -= parseFloat(quantity)
                                                                    $("#Bundles").text(BundlesLimit);
                                                                }

                                                                $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                                                                $("#BundlesInUse").text(BundlesLimitInUse);
                                                            }
                                                        });
                                                    }
                                                });
                                            }

                                        });
                                }
                                else
                                {
                                    /* Pakiet nie ma oświadczeń */
                                    var id = thisInput2.attr('id').substring(14);
                                    var isAcceptedProductsPronouncments = true;

                                    var count = $("#bundle_products_" + id + " .bundle_tender_pronouncment").length;
                                    var counter = 0;

                                    $("#bundle_products_" + id + " .bundle_tender_pronouncment").each(function(){
                                        var tenderPronouncment = $(this).val();
                                        if(tenderPronouncment != undefined && tenderPronouncment != "" && isAcceptedProductsPronouncments == true){
                                            jConfirm(pronouncment, '', function(r) {
                                                if(!r){
                                                    thisInput.removeAttr('checked');
                                                    isAcceptedProductsPronouncments = false;
                                                    return;
                                                }
                                                counter = counter + 1;

                                                if(counter == count)
                                                { 
                                                    if(!isAcceptedProductsPronouncments)
                                                        return;
                        

                                                    BundlesLimitInUse = BundlesLimitInUse + parseFloat(quantity);

                                                    if($("#IsEdit").val().toLowerCase() == 'false')
                                                        $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                                                    else
                                                    {
                                                        BundlesLimit -= parseFloat(quantity);
                                                        $("#Bundles").text(BundlesLimit);
                                                    }

                                                    $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                                                    $("#BundlesInUse").text(BundlesLimitInUse);
                                                }
                                            });
                                        }
                                    });
                                    
                                    /* Nie było oświadczeń dla pakietu */
                                    if (counter == 0){
                                        BundlesLimitInUse = BundlesLimitInUse + parseFloat(quantity);

                                        if($("#IsEdit").val().toLowerCase() == 'false')
                                            $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                                        else
                                        {
                                            BundlesLimit -= parseFloat(quantity);
                                            $("#Bundles").text(BundlesLimit);
                                        }

                                        $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                                        $("#BundlesInUse").text(BundlesLimitInUse);
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        SetInformationBox(1, '@Html._("Masz za mało pakietow")');
                        $(this).removeAttr('checked');
                    }
                }
                else
                {

                 if(!isNew && $("input[id^='tender_bundle_']:checked").length == 0)
                    {
                        thisInput2.attr("checked","checked");
                        SetInformationBox(1,'@Html._("Nie możesz odznaczyć wszystkich produktów. Przynajmniej jeden musi być zaznaczony.")');
                    }
                    else
                    {
                        if($("#IsEdit").val().toLowerCase() == 'false')
                        {
                            if($(this).closest("td").find(".hasEmployeeOrVIPCard").val().toLowerCase() == 'true')
                            {
                            //zakomentowane w związku z błędem 4613
    //                            if($("#OtherCardsWithEmployeeOrVIPCard").val().toLowerCase() == 'true') //jeśli karty typu kid, kids ,osTow mozna zamawiac jedynie z karta pracownik lub vip
    //                            {
    //                                SetInformationBox(2, "Odznaczyłeś/-aś zamówienie karty typu \"Pracownik\" lub 'VIP'. Ponieważ ustawienia nie pozawalają na zamawianie pozostałych typów kart bez karty 'Pracownik' lub 'VIP', zamówienia takie zostaną odznaczone.");
    //                                    $(".isMultisportCard").each(function(index,element){
    //                                        $(element).closest("td").find("input[id^='platofrm_tender_']").removeAttr("checked");
    //                                    });
    //                            }
                            }
                        }
                        startSpinner();
                        $.post('@Url.Action("CanOrderBundle", "Home")', bundles, function(data)
                        {
                            stopSpinner();
                            if(data != 'OK'){
                                if (data == 'CannotDecreaseSmsProduct')
                                    thisInput2.attr('checked',true);

                                if (data != 'NoPhoneDefined'){
                                    SetInformationBox(1, getMessage(data));
                                }
                                else{
                                    popupChangePhone(getMessage(data));
                                }
                            }
                            else{
                                BundlesLimitInUse = BundlesLimitInUse - parseFloat(quantity);
                                if($("#IsEdit").val().toLowerCase() == 'false'){
                                    $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                                    $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                                }
                                else{
                                    BundlesLimit += parseFloat(quantity)
                                    $("#Bundles").text(BundlesLimit);
                                    $("#Bundles2").text(BundlesLimit);
                                }
                                $("#BundlesInUse").text(BundlesLimitInUse);
                            }
                        });
                    }
                }
            });

            // Zwiększanie ilości pakietu
            $(".incrementQuantityBundle").live('click',function(){
                var bundlesLeft = $("#Bundles").text();
                var $tb_bundle = $(this).closest('.bundle-div').find('input[id^="bundle_quantity_"]');
                var actual = $tb_bundle.val();
                var max = $(this).closest('.bundle-div').find('.max_quantity').val();
                if(parseFloat(bundlesLeft) > 0){
                    var newVal = parseFloat(actual) + 1;
                    if($("#IsEdit").val().toLowerCase() == 'false' || ($("#IsEdit").val().toLowerCase() == 'true' && newVal <= max))
                    {
                            $tb_bundle.val(newVal);
                            if($(this).closest('.bundle-div').find("input[id^='tender_bundle_']").is(":checked") == true)//attr('checked') == 'checked')
                            {
                                BundlesLimitInUse = BundlesLimitInUse + 1;
                                if($("#IsEdit").val().toLowerCase() == 'false')
                                {
                                     $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                                     $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                                     }
                                else
                                {
                                    BundlesLimit -= parseFloat(1);
                                    $("#Bundles").text(BundlesLimit);
                                    $("#Bundles2").text(BundlesLimit);
                                }
                                
                                $("#BundlesInUse").text(BundlesLimitInUse);
                            }
                            $(this).closest('tr').find('.quantity').trigger('keyup');

                            //Przy zwiększaniu pakietu wywołujemy anOrderBundle
                            bundles += "&fromJS=true";
                            bundles += '&operation=';
                            bundles += $(this).parent().prev().find(':checkbox').is(":checked") == true ? 'checked,':'unchecked,';
                            bundles += $("#IsEdit").val().toLowerCase() == 'false' ? 'new,' : 'update,';
                            bundles += 'minus';

                            if($(this).parent().prev().find(':checkbox').is(":checked") == true)
                            {
                                var $tb_chb = $(this).parent().prev().find(':checkbox');
                                var bundles = "";
                                var counter = 0;

                                $("input[id^='tender_bundle_']:checked").each(function(index, Element) { 
                                    bundles += '&bundleOrders[' + counter + '].TenderBundleId=' + $(Element).attr('id').substring(14);
                                    bundles += '&bundleOrders[' + counter + '].Quantity=' + $("input[id='bundle_quantity_" + $(Element).attr('id').substring(14) + "']").val();
                                    counter += 1;
                                });

                                bundles += '&bundleId=' + $tb_chb.attr('id').substring(14);
                                bundles += '&quantity=' + newVal;
                                bundles += '&platformId=' + currentPlatformId;

                                if(!isNew)
                                    bundles += "&isActualization=true";
                                else
                                    bundles += "&isActualization=false";

                                bundles += '&fromJS=true&operation=checked,new,plus';

                                startSpinner();
                                $.post('@Url.Action("CanOrderBundle", "Home")', bundles, function(data)
                                {
                                    stopSpinner();
                                    if(data != 'OK'){
                                        //$tb_chb.removeAttr('checked');

                                    if (data != 'NoPhoneDefined'){
                                        SetInformationBox(1, getMessage(data));
                                    }
                                    else{
                                        popupChangePhone(getMessage(data));
                                    }
                                     
                                    /* Jeśli zabrakło pakietu SMS to zmniejszamy ilość o 1 */
                                    if(data =='NoSmsAvail'){
                                        $tb_bundle.val(actual);
                                        BundlesLimitInUse = BundlesLimitInUse -1;
                                        if($("#IsEdit").val().toLowerCase() == 'false')
                                             $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                                        else
                                        {
                                            BundlesLimit += parseFloat(1);
                                            $("#Bundles").text(BundlesLimit);
                                        }
                                        $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                                        $("#BundlesInUse").text(BundlesLimitInUse);
                                    }

                                    }
                                });
                                
                            }
                    }
                }
            });

            $(".decrementQuantityBundle").live('click',function(){
                var bundlesLeft = $("#Bundles").text();
                var actual = $(this).closest('.bundle-div').find('input[id^="bundle_quantity_"]').val();
                if(parseFloat(actual) > 1){
                    var newVal = parseFloat(actual) - 1;
                    var $tb_bundle = $(this).closest('.bundle-div').find('input[id^="bundle_quantity_"]');

                    $tb_bundle.val(newVal);
                    if($(this).closest('.bundle-div').find("input[id^='tender_bundle_']").is(":checked") == true)//attr('checked') == 'checked')
                    {
                        BundlesLimitInUse = BundlesLimitInUse - 1;
                        if($("#IsEdit").val().toLowerCase() == 'false')
                        {
                            $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                            $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                        }
                        else
                        {
                            BundlesLimit += parseFloat(1);
                            $("#Bundles").text(BundlesLimit);
                            $("#Bundles2").text(BundlesLimit);
                        }
                        
                        $("#BundlesInUse").text(BundlesLimitInUse);
                        //$("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                        //$("#BundlesInUse").text(BundlesLimitInUse);
                    }
                    $(this).closest('tr').find('.quantity').trigger('keyup');

                    //Przy zmniejszamnuiu pakietu wywołujemy anOrderBundle
                    var bundles = "";
                    var counter = 0;
                    bundles += "&fromJS=true";
                    bundles += '&operation=';
                    bundles += $(this).parent().prev().find(':checkbox').is(":checked") == true ? 'checked,':'unchecked,';
                    bundles += $("#IsEdit").val().toLowerCase() == 'false' ? 'new,' : 'update,';
                    bundles += 'minus';

                    if($(this).parent().prev().find(':checkbox').is(":checked") == true)
                    {
                        var $tb_chb = $(this).parent().prev().find(':checkbox');

                        $("input[id^='tender_bundle_']:checked").each(function(index, Element) { 
                            bundles += '&bundleOrders[' + counter + '].TenderBundleId=' + $(Element).attr('id').substring(14);
                            bundles += '&bundleOrders[' + counter + '].Quantity=' + $("input[id='bundle_quantity_" + $(Element).attr('id').substring(14) + "']").val();
                            counter += 1;
                        });

                        bundles += '&bundleId=' + $tb_chb.attr('id').substring(14);
                        bundles += '&quantity=' + newVal;
                        bundles += '&platformId=' + currentPlatformId;

                        if(!isNew)
                            bundles += "&isActualization=true";
                        else
                            bundles += "&isActualization=false";

                        startSpinner();
                        $.post('@Url.Action("CanOrderBundle", "Home")', bundles, function(data)
                        {
                        stopSpinner();
                            if(data != 'OK'){
                                //$tb_chb.removeAttr('checked');
                                 //$tb_bundle.val(actual);

                                if (data != 'NoPhoneDefined'){
                                    SetInformationBox(1, getMessage(data));
                                }
                                else{
                                    popupChangePhone(getMessage(data));
                                }

                            }else{
                                //$tb_bundle.val(newVal);
                            }
                            
                        });
                                
                    }
                }
            });

            $("#save_order_bundles").live('click',function(){
                if($(this).attr('disabled') == 'disabled')
                    return;

                $(this).attr('disabled','disabled');

                var thisButon = $(this);

                var isValid = true;
                $("#HolderNameMessage").hide();
                $("#PronouncementMessage").hide();

                $("input[id^='platform_pronouncement_']").each(function(){
                    if($(this).attr('checked') != 'checked')
                    {
                        isValid = false;
                        $("#PronouncementMessage").show();
                        thisButon.removeAttr('disabled');
                        return;
                    }
                });

                $("input.holderName[id^='tbundle_']").each(function(){
                    if($(this).val() == "")
                    {
                        var ids = $(this).attr('id').split('_'); //tBundle id => ids[1], cTender id => ids[3]

                        if($("#tender_bundle_" + ids[1]).attr('checked') == 'checked')
                        {
                            isValid = false;
                            $("#HolderNameMessage").show();
                            thisButon.removeAttr('disabled');
                            return;
                        }
                    }
                });

                if(isValid)
                {
                    var bundles = "";
                    var counter = 0;

                    $("input[id^='tender_bundle_']:checked").each(function () { 
                        bundles += '&bundleOrders[' + counter + '].TenderBundleId=' + $(this).attr('id').substring(14);
                        bundles += '&bundleOrders[' + counter + '].Quantity=' + $("input[id='bundle_quantity_" + $(this).attr('id').substring(14) + "']").val();
                        
                        var tenderCounter = 0;

                        $(this).closest('.bundle-container').find('.holderNameConatainer').each(function(){ 
                            bundles += "&bundleOrders[" + counter + "].TendersInBundle[" + tenderCounter + "].CustomerTenderId=" + $(this).attr('id').substring(12);
                            
                            var holderCounter = 0;

                            $(this).find('.holderName').each(function(){
                                bundles += "&bundleOrders[" + counter +"].TendersInBundle[" + tenderCounter + "].HolderNames[" + holderCounter + "].Name=" + $(this).val();
                                bundles += "&bundleOrders[" + counter +"].TendersInBundle[" + tenderCounter + "].HolderNames[" + holderCounter + "].Surname=" + $(this).closest('tr').find('.holderSurname').val();
                                holderCounter = holderCounter + 1;
                            });
                            tenderCounter = tenderCounter + 1;
                        });

                        counter = counter + 1;
                    });

                    bundles += "&platformId=" + currentPlatformId; //$("#taby-top li.active a[id^='tab-platform-']").attr('id').substring(13);

                    var employeeOrderId = parseInt($("#EmployeeOrderId").val());
                    if(employeeOrderId > 0)
                    {
                        bundles += "&employeeOrderId=" + employeeOrderId;
                        if($("#IsEdit").val().toLowerCase() == 'true')
                        {
                            $.post('/Kafeteria/' + lang + '/Home/UpdateProductsBundles', bundles ,function(){                                                                                                 
                                $("#tab-platform-" + currentPlatformId).trigger('click');
                                ShowInformationBox();
                            });
                        }
                        else
                        {
                            $.post('/Kafeteria/' + lang + '/Home/UpdateOrderBundles', bundles ,function(){                                                                                                 
                                $("#tab-platform-" + currentPlatformId).trigger('click');
                                ShowInformationBox();
                            });
                        }
                    }
                    else
                    {
                        $.post('/Kafeteria/' + lang + '/Home/SaveOrderBundles', bundles ,function(){                                                                                                                 
                            $("#tab-platform-" + currentPlatformId).trigger('click');
                            ShowInformationBox();                            
                        });
                    }
                }
            });

            /***koniec pakiety***/

            $('#orderResign').live('click',function(){
                var confirmation;

                if($(".isMultiDeal[value='True']").closest('td').find(".canResignMD[value='False']").length == 0)
                {
                    confirmation = '@Html._("Czy na pewno chcesz zrezygnować z bieżącego zamowienia?")';
                }
                else
                {
                    var products = '';
                    $(".isMultiDeal[value='True']").closest('td').find(".canResignMD[value='False']").each(function(index,element){
                        if($(this).closest('td').find("input[id^='platofrm_tender_']").is(":checked"))
                            products += $(element).closest('tr').find('td').find('.nameLabel').text() + '@Html._("w ilości: ")' + $(element).closest('td').find('.minQuantityMD').val() + "\n";
                    });

                    if(products != '')
                        confirmation = '@Html._("Rezygnacja nie nastąpi z następujących produktow:")' + "\n" + products + 
                                    '@Html._("Czy kontynuować?")';
                    else
                        confirmation = '@Html._("Czy na pewno chcesz zrezygnować z bieżącego zamowienia?")';
                }

                if(confirm(confirmation))
                {
                    var employeeOrderId = $("#EmployeeOrderId").val();
                    $.post('/Kafeteria/' + lang + '/Home/OrderResign', { employeeOrderId: employeeOrderId }, function(){
                        $("#tab-platform-" + currentPlatformId).trigger('click');
                        ShowInformationBox();

                        refreshInfo();
                    });
                }
            });

            /*****koniec: obsługa zamówienia*****/


            $("a[id^='multisport_']").live('click',function(){
                var cardId = $(this).attr('id').substring(11);
                if(confirm('@Html._("Czy na pewno chcesz zrezygnować z tej karty multisport?")'))
                {
                    startSpinner();
                    $.post('/Kafeteria/' + lang + '/Home/MultisportCardResignation', {cardId: cardId}, function(){
                        $("#content-karty").load('/Kafeteria/' + lang + '/Home/MultisportCards', function() { stopSpinner(); });
                        $("a[id^='tab-platform-" + currentPlatformId + "']").trigger('click');
                        //var panelGraphic = getPlatformGraphic(currentPlatformId);
                        //ReloadPlatformGUI(panelGraphic);
                    });
                }
            });

            $("a[id^='duplicate_multisport_']").live('click',function(){
                var cardId = $(this).attr('id').substring(21);
                if(confirm('@Html._("Czy na pewno chcesz złożyć zamowienie na duplikat?")'))
                {
                    $.get('/Kafeteria/' + lang + '/Home/MultisportCardDuplicate', {cardId: cardId},function(data){
                        $("#content-karty").html(data);
                        ShowInformationBox();
                        var panelGraphic = getPlatformGraphic(currentPlatformId);
                        ReloadPlatformGUI(panelGraphic);
                    });
                }
            });

            $("#orderDuplicate").live("click",function(){
                $.post('@Url.Action("MultisportCardDuplicate")', $("#duplicateForm").serialize(), function(data){
                    if(data == "OK")
                    {
                        SetInformationBox(2,'@Html._("Złożono zamówienie na duplikat")');
                        $("#content-karty").load('/Kafeteria/' + lang + '/Home/MultisportCards');
                        var panelGraphic = getPlatformGraphic(currentPlatformId);
                        ReloadPlatformGUI(panelGraphic);
                    }
                    else
                    {
                        $("#content-karty").html(data);
                        var panelGraphic = getPlatformGraphic(currentPlatformId);
                        ReloadPlatformGUI(panelGraphic);
                    }
                });
            });

            $("#cancelDuplicate").live("click",function(){
                $("#content-karty").load('/Kafeteria/' + lang + '/Home/MultisportCards');
                var panelGraphic = getPlatformGraphic(currentPlatformId);
                ReloadPlatformGUI(panelGraphic);
            });


            $("#currentOrderTab").live('click',function(){
                $(".submenu ul li a").css('color', 'black');
                $(this).css('color','#FE9B00');

                var url = "/Kafeteria/" + lang +"/Home/PlatformNewOrder";
                getSubTabContent(url, currentPlatformId, true, false);
            });

            $("#lastOrderTab").live('click',function(){
                $(".submenu ul li a").css('color', 'black');
                $(this).css('color','#FE9B00');

                var url = "/Kafeteria/" + lang +"/Home/PlatformLastOrder";
                getSubTabContent(url, currentPlatformId, false, true);
            });

            $("#refreshMDCounter").live('click', function () {
                var ctsfId = $("#MDCTSFId").val();
                url = "/Kafeteria/" + lang + "/Home/GetMDCounter";
                $.post(url, { ctsfId: ctsfId }, function (data) {
                    $("#MDCounter").text(data);
                });
            });

            $("#chargeSPLimit").live('click',function(){
                $.post('@Url.Action("ChargeLimit")',{ platformId: currentPlatformId }, function(data){
                    $(".platformContainer").html(data);
                    var panelGraphic = getPlatformGraphic(currentPlatformId);
                    ReloadPlatformGUI(panelGraphic);
                });
            });

            $("#cancelCharge").live('click', function(){
                $("a[id='tab-platform-" + currentPlatformId + "']").trigger('click');
            });
//            $("#orderCharge").live('click',function(){
//                $.post('@Url.Action("Pay", "Payment")', { platformId: currentPlatformId, limitAmount }, function(data){
//                    window.location = data;
//                });
//            });
            
            $("#returnToOrderForm").live('click',function()
            {
                $("a[id='tab-platform-" + currentPlatformId + "']").trigger('click');
            });
		});       

    
        function przeliczLimity(callEndFunctionId)
        {

                var empOrderId = $("#EmployeeOrderId").val();
                var tenders = "";
                var counter = 0;
                $("input[id^='platofrm_tender_']:checked").each(function () {
                    tenders += "&productOrders[" + counter + "].Quantity=" + $(this).closest('tr').find('.quantity').val();
                    tenders += "&productOrders[" + counter + "].CustomerTenderSourceFinanceId=" + $(this).closest('tr').find("input[id^='ctsf_']").val();
                                                                
                    counter = counter + 1;
                });

                if(!isNew)
                {
                    tenders += "&platformId=" + currentPlatformId + "&empOrderId=" + empOrderId + "&isActualization=true";
                }
                    else
                {
                    tenders += "&platformId=" + currentPlatformId + "&empOrderId=" + empOrderId + "&isActualization=false";
                }

                $.post("/Kafeteria/" + lang +"/Home/GetCurrentUsedLimits", tenders , function(data){
                    ZFSSLimitInUse = 0;//data['ZFSSLimitInUse'];
                    SOLimitInUse = 0;//data['SOLimitInUse'];
                    SPLimitInUse = 0;//data['SPLimitInUse'];

                    ZFSSLimit = data['ZFSS_Left'];
                    SOLimit = data['SO_Left'];
                    SPLimit = data['SP_Left'];

                    SPToPay = data['SPToPay'];

                    if(SPToPay > 0)
                    {
                        $("#LimitToPay").text(SPToPay.toFixed(2).toString().replace(".",","));
                        $("#toPayText").show();
                        $("#payuInfo").show();
                    }
                    else
                    {
                        $("#LimitToPay").text(SPToPay.toFixed(2).toString().replace(".",","));
                        $("#toPayText").hide();
                        $("#payuInfo").hide();
                    }

                    BundlesLimit = data['Bundles_Left'];
                    BundlesLimitInUse = 0;
                    if(!isNew)
                    {
                        BundlesLimitInUse = data['Bundles'];
                    }

                    $("#Bundles").text(BundlesLimit)
                    $("#Bundles2").text(BundlesLimit)
                    $("#BundlesInUse").text(BundlesLimitInUse)

                    LiczLimity(SPToPay,SPLimit,data['SPLimitInUse']);

                    if(callEndFunctionId != undefined && callEndFunctionId != null && callEndFunctionId != '')
                    {
                        przeliczLimityEndFunction(callEndFunctionId)
                    }
                    
                    if(testvar){
                        var curZFSS = parseFloat($("#ZFSSLimit").text());
                        var curSO = parseFloat($("#SOLimit").text());
                        var curSP = parseFloat($("#SPLimit").text()); 
            
                        if(curZFSS < 0 || curSO < 0 || curSP < 0)
                        {            
                            SetInformationBox(1, '@Html._("Masz za mało dostępnych limitow")');                
                            $("#" + inputId).attr('checked', false);                   
                            przeliczLimity();
                            unlockExcludingProducts($("#" + inputId));
                        }       
                        testvar = false;
                        $.fancybox.close();
                    }
                });
                
        }

        function przeliczLimityEndFunction(callEndFunctionId)
        {
            //tutaj warunki na canbuy i to pay
            //todo: zrobic flage w sources zwracanych z kontrolera i wyswietlac wtedy komunikat ze malo limitow (lub sprawdzac czy ...inUse nie jest ujemne
            
            if((ZFSSLimit < ZFSSLimitInUse || SOLimit < SOLimitInUse || (SPLimit + SPToPay < SPLimitInUse)) && $("#" + callEndFunctionId).closest('tr[id^="platform_tender_row_"]').find("input[id^='platofrm_tender_']").attr('checked') == 'checked')
                {
                    SetInformationBox(1, '@Html._("Masz za mało dostępnych limitow")');
                    $("#" + callEndFunctionId).val('1');
                    
                    var holderNameTBox = 'N / D';
                    if($("#" + callEndFunctionId).closest('tr[id^="platform_tender_row_"]').find("input[id^='personal']").val().toString().toLowerCase() == 'true')
                        holderNameTBox = '<table><tr><td style="margin: 0px 2px 0px 0px; padding: 0px;" ><input type="text" style="width: 90%; margin-bottom: 2px;" class="holderName" /></td><td style="margin: 0px; padding: 0px;"><input type="text" style="width: 90%; margin-bottom: 2px;" class="holderSurname" /></td></tr></table>';

                    $("#" + callEndFunctionId).closest('tr[id^="platform_tender_row_"]').find(".holderNameConatainer").html(holderNameTBox);
                    przeliczLimity();
                }
                
                
                if((ZFSSLimit < ZFSSLimitInUse || SOLimit < SOLimitInUse || (SPLimit < SPLimitInUse)) && $("#" + callEndFunctionId).closest('tr[id^="platform_tender_row_"]').find("input[id^='platofrm_tender_']").attr('checked') == 'checked')
                {
                    //SetInformationBox(1, '@Html._("Masz za mało dostępnych limitow")');
                    $("#" + callEndFunctionId).closest('tr').find("input[id^='platofrm_tender_']").removeAttr('checked');
                    przeliczLimity();
                }  
               
                }

        function LiczLimity(SPToPay,SPLimit,SPLimitInUseOrginal)
        {
            $("input[id^='platofrm_tender_']:checked").each(function(){
                var ptNo = $(this).attr('id').substring(16);

                var _zfss = $("tr[id='platform_tender_row_" + ptNo + "'] .ptZFSS").text();
                if(_zfss == "")
                    _zfss = "0";
                var _so = $("tr[id='platform_tender_row_" + ptNo + "'] .ptSO").text();
                if(_so == "")
                    _so = "0";
                var _sp = $("tr[id='platform_tender_row_" + ptNo + "'] .ptSP").text();
                if(_sp == "")
                    _sp = "0";

                _zfss = _zfss.replace(",",".");
                _so = _so.replace(",",".");
                _sp = _sp.replace(",",".");

                var _quantity = $("tr[id='platform_tender_row_" + ptNo + "'] .quantity").val();
                        
                ZFSSLimitInUse = ZFSSLimitInUse + parseFloat(_zfss).toFixed(2) * parseFloat(_quantity);
                SOLimitInUse = SOLimitInUse + parseFloat(_so).toFixed(2) * parseFloat(_quantity);
                SPLimitInUse = SPLimitInUse + parseFloat(_sp).toFixed(2) * parseFloat(_quantity);
            });

            var tmpZFSSLimitInUse = parseFloat(ZFSSLimitInUse).toFixed(2).toString().replace(".",",");
            var tmpSOLimitInUse = parseFloat(SOLimitInUse).toFixed(2).toString().replace(".",",");
            var tmpSPLimitInUse = parseFloat(SPLimitInUse).toFixed(2).toString().replace(".",",");

            var tmpZFSSLimit = parseFloat(ZFSSLimit - ZFSSLimitInUse).toFixed(2).toString().replace(".",",");
            var tmpSOLimit = parseFloat(SOLimit - SOLimitInUse).toFixed(2).toString().replace(".",",");
            var tmpSPLimit = parseFloat(SPLimit - SPLimitInUse).toFixed(2).toString().replace(".",",");

            $("#ZFSSLimitInUse").text(tmpZFSSLimitInUse);
            $("#SOLimitInUse").text(tmpSOLimitInUse);
            
            if(SPToPay > 0)
            {
                $("#SPLimitInUse").text(SPLimitInUseOrginal.toFixed(2).toString().replace(".",","));
            }
            else
            {
                $("#SPLimitInUse").text(tmpSPLimitInUse);
            }

            $("#ZFSSLimit").text(tmpZFSSLimit);
            $("#SOLimit").text(tmpSOLimit);
            
            if(SPToPay > 0)
            {
                $("#SPLimit").text((SPLimit - SPLimitInUseOrginal).toFixed(2).toString().replace(".",","));
            }
            else
            {
                $("#SPLimit").text(tmpSPLimit);
            }

            if(changeGorneLimity == true)
            {
                changeGorneLimity = false;
                $("#L_ZFSS").text(tmpZFSSLimit);
                $("#L_SO").text(tmpSOLimit);
                $("#L_SP").text(tmpSPLimit);
            }
        }

        function getMessage(code)
        {
            if(code == 'InvalidCTSF')
            {
                return 'Niepoprawne dane.';
            }
            if(code == 'ExceedQuantity')
            {
                return 'Przekroczono dostępną ilość usługi/produktu.';
            }
            if(code == 'InvalidPeriodService')
            {
                return 'Usługa okresowa została już zamówiona, nie można jej zamówić ponownie dopóki nie skończy się czas jej trwania.';
            }
            if(code == 'NoEmployeeOrVIPCard')
            {
                return '@Html._("Aby zamówić tą kartę multisport musisz zamówić kartę 'Pracownik' lub 'VIP'.")';
            }
            if(code == 'AlreadyHaveVIPOrEmployeeCard')
            {
                return "Możesz posiadać tylko jedną kartę typu 'Pracownik' lub 'VIP'.";
            }
            if(code == 'ExceedQuantityKidKids')
            {
                return "Przekroczono dostępną ilość kart 'Dziecko' i 'Kids'.";
            }
            if(code == 'ExceedQuantityPerson')
            {
                return "Przekroczono dostępną ilość kart typu 'Osoba towarzysząca'.";
            }
            if(code == 'ExceedQuantityKid')
            {
                return "Przekroczono dostępną ilość kart typu 'Dziecko'.";
            }
            if(code == 'ExceedQuantityKids')
            {
                return "Przekroczono dostępną ilość kart typu 'Kids'.";
            }
            if(code == 'ExceededQuantityMD')
                return "Przekroczono dostępną ilość produktów.";

            if (code == 'NoPhoneDefined')
                return '@Html._("Nie możesz zamówić produktu SMS jeśli nie zdefiniowano numeru telefonu. Uzupełnij dane poniżej")';

            if (code =='NoSmsAvail')
                return '@Html._("Nie możesz zamówić produktu/pakietu SMS ponieważ zabrakło kodów SMS")';

            if (code =='CannotDecreaseSmsProduct')
                return '@Html._("Nie można zmniejszyć ilości produktu SMS jeżeli kody zostały pobrane od razu!")';

            if(code == 'ExcludingGroupError')
                return '@Html._("Nie możesz wybrać tego produktu ponieważ należy on do grupy produktów wykluczających się, z której został już wybrany inny produkt.")';
        }

		function getPlatformGraphic(platformId)
		{
			for(var i = 0; i < platformGraphicList.length; i++)
			{
				if(platformGraphicList[i].PlatformId == platformId)
				{
					return platformGraphicList[i];
				}
			}
		}

        function getSubTabContent(_url, pId, is_new,readOnly)
        {
            startSpinner();
            isNew = is_new;
            var panelGraphic = getPlatformGraphic(currentPlatformId);

            if(opt == 'checkChargeStatus')
            {
                $("#loading").css('display','none');
                opt = '';
            }
            else
            {
            $.post(_url,{ platformId: pId, isReadOnly: readOnly }, function(data){

                /* Serce płacze, że takie n00b0we rozwiązanie ale nie szło inaczej */
                if (data.toString().indexOf("logowanie-box") != -1){
                    window.location.reload();

                }else{
                $(".platformContainer").html('');
                            $("#platforma-" + pId + " .platformContainer").html(data);
                        
                            changeGorneLimity = true;

                            ZFSSLimit = parseFloat($("#ZFSSLimit").text()).toFixed(2);
                            SOLimit = parseFloat($("#SOLimit").text()).toFixed(2);
                            SPLimit = parseFloat($("#SPLimit").text()).toFixed(2);
                            ZFSSLimitInUse = 0;
                            SOLimitInUse = 0; 
                            SPLimitInUse = 0;

                            BundlesLimit = parseFloat($("#Bundles").text());
                            BundlesLimitInUse = 0;

                            maxKidAndKidsCount = parseFloat($("#KidAndKidsMaxCount").val()); 
                            orderedKidAndKidsCount = 0;

                            $(".kidorkids:checked").map(function(index, element){
                                if($(element).closest("input[id^='platofrm_tender_']").attr('checked') == 'checked')
                                {
                                    orderedKidAndKidsCount += parseFloat($(element).closest(".quantity").val());
                                }
                            });

                            $("input[id^='tender_bundle_']:checked").each(function(){
                                var ptNo = $(this).attr('id').substring(14);
                                var _quantity = $("#bundle_quantity_" + ptNo).val();
                        
                                BundlesLimitInUse = BundlesLimitInUse + parseFloat(_quantity);
                            });

                            if($("#IsDetailsMode").val().toLowerCase() == 'true')
                            {
                                $("input[type='checkbox']").attr('disabled','disabled');
                                $(".incrementQuantityBundle").attr('disabled','disabled');
                                $(".incrementQuantity").attr('disabled','disabled');
                                $(".decrementQuantity").attr('disabled','disabled');
                                //$(".quantity").attr('readonly','readonly');
                                $(".decrementQuantityBundle").attr('disabled','disabled');
                                $(".holderName").attr('disabled','disabled');
                                $(".holderSurname").attr('disabled','disabled');
                            }
                        


                            $("#Bundles").text((BundlesLimit - BundlesLimitInUse));
                            $("#Bundles2").text((BundlesLimit - BundlesLimitInUse));
                            $("#BundlesInUse").text(BundlesLimitInUse);

                            przeliczLimity(isNew);

                            $("a.more-window").fancybox({
				                'width'				: 720,
				                'height'			: 460,
				                'overlayColor'      : '#fff',
				                'autoDimensions'    : false,
				                'autoScale'			: false,
				                'transitionIn'		: 'none',
				                'transitionOut'		: 'none',
				                'type'				: 'ajax'
			                });

                            $("a.change-frequency").fancybox({
				                'width'				: 600,
				                'height'			: 270,
				                'overlayColor'      : '#fff',
				                'autoDimensions'    : false,
				                'autoScale'			: false,
				                'transitionIn'		: 'none',
				                'transitionOut'		: 'none',
				                'type'				: 'ajax'
			                });

                              $("a.employee-declare-source-finance").fancybox({
				                'width'				: 280,
				                'height'			: 300,
				                'overlayColor'      : '#fff',
				                'autoDimensions'    : false,
				                'autoScale'			: false,
				                'transitionIn'		: 'none',
				                'transitionOut'		: 'none',
				                'type'				: 'ajax'
			                });
                            
                            if(showSessionDeclarationPopup == 'true')
                            {
                                $("a.change-frequency").trigger('click');
                                showSessionDeclarationPopup = false;
                            }

                            /***START: jesli podglad to blokujemy mozliwosc domawiania produktow***/
                            if(!isNew)
                            {
                                $("input[id^='platofrm_tender_']").each(function(){
                    
                                    if($(this).attr("checked") != "checked")
                                    {
                                        $(this).attr("disabled","disabled");
                                    }

                                    var currentQuantity = $(this).closest("tr").find(".quantity").val();
                                    $(this).closest("tr").find(".max_quantity").val(currentQuantity);
                                });

                                $("input[id^='tender_bundle_']").each(function(){
                    
                                    if($(this).attr("checked") != "checked")
                                    {
                                        $(this).attr("disabled","disabled");
                                    }

                                    var currentQuantity = $(this).closest("td").find(".quantity").val();
                                    $(this).closest("tr").find(".max_quantity").val(currentQuantity);
                                });
                            }
                            /***END: jesli podglad to blokujemy mozliwosc domawiania produktow***/
							//$("#loading").css('display','none');
                            ReloadPlatformGUI(panelGraphic);
                            refreshInfo();
                }
                stopSpinner();
            });
            }
        }
    
        function ReloadPlatformGUI(panelGraphic){
            if(panelGraphic != null)
            {
                //$(".bg-img").css("background-image","url('" + panelGraphic.TextureUrl + "')");
                $("body").removeClass().addClass("bg-img-" + panelGraphic.PlatformId);

				$(".color").css("color","#"+panelGraphic.ForegroundColor);
                $("fieldset").css("border-color","#"+panelGraphic.ForegroundColor);
				$("#top-menu ul li.color a").css("color","#"+panelGraphic.ForegroundColor);
				$("#mainmenu ul li a").css("color","#"+panelGraphic.ForegroundColor);
				$("#platformmenu ul li a").css("color","#"+panelGraphic.ForegroundColor);
				$(".sub-menu ul li a").css("color","#"+panelGraphic.ForegroundColor);
                $(".sub-menu ul li.active a").css("color","#FE9B00");
				$(".do-content h2").css("color","#"+panelGraphic.ForegroundColor);
				$(".do-content h1").css("color","#"+panelGraphic.ForegroundColor);
				$(".suma").css("color","#"+panelGraphic.ForegroundColor);
				$(".cena-big").css("color","#"+panelGraphic.ForegroundColor);
				$(".ui-tabs .ui-tabs-nav li a").css("color","#"+panelGraphic.ForegroundColor);
				$("#logowanie-box h1").css("color","#"+panelGraphic.ForegroundColor);
                $(".pasek h3 a").css("color","#"+panelGraphic.ForegroundColor);
                $("#komunikaty").css("color","#"+panelGraphic.ForegroundColor);
                $(".xbutton").css("color","#"+panelGraphic.ForegroundColor);
                
				$("#witaj").css('font-family',panelGraphic.Font);
				$("#top-menu ul li a").css('font-family',panelGraphic.Font);
				$("#platformmenu  ul li a").css('font-family',panelGraphic.Font);
				$("#komunikaty h2").css('font-family',panelGraphic.Font);
				$("#komunikaty a").css('font-family',panelGraphic.Font);
				$(".sub-menu ul li a").css('font-family',panelGraphic.Font);
				$(".do-content h2").css('font-family',panelGraphic.Font);
				$(".do-content h1").css('font-family',panelGraphic.Font);
				$(".do-content .caption-1").css('font-family',panelGraphic.Font);
				$(".pasek h3").css('font-family',panelGraphic.Font);
				$(".pasek h3 a").css('font-family',panelGraphic.Font);
				$(".zawartosc  .ui-state-active h3 a").css('font-family',panelGraphic.Font);
				$(".zawartosc  .selected h3 a").css('font-family',panelGraphic.Font);
				$(".pasek-2 h3").css('font-family',panelGraphic.Font);
				$(".pasek-2 h3 a").css('font-family',panelGraphic.Font);
				$(".suma ").css('font-family',panelGraphic.Font);
				$(".cena-big ").css('font-family',panelGraphic.Font);
				$(".xbutton").css('font-family',panelGraphic.Font);
				$(".infolinia ").css('font-family',panelGraphic.Font);
				$(".ui-tabs .ui-tabs-nav li a").css('font-family',panelGraphic.Font);
				$("#logowanie-box h1 ").css('font-family',panelGraphic.Font);

                $(".bg-color").css("background-color","#"+panelGraphic.BackgroundColor);
				$(".kolor-btn.xbutton").css("background-color","#"+panelGraphic.BackgroundColor);
                    


                /* Ogarnianie 3 trybów wyświetlania na stronie platformy */
                if (panelGraphic.PlatformLayoutType != null){
                    if (panelGraphic.PlatformLayoutType == 0){
                        $('#banner-1').hide();
                        $('#logo-1').css('float','left');
                        $('#logo-2').css('float','right');

                        /* Sprawdzenie czy platforma ma obrazki, a jak nie to ładujemy domyślne. */
                        if (panelGraphic.PlatformLeftUrl != null){
                            $("#logo-1 img").attr("src", panelGraphic.PlatformLeftUrl);
                        }else{
                            $("#logo-1 img").attr("src",'@Url.Content("~/Content/kafeteria/images/logo-1.png")');
                        }

                        if (panelGraphic.PlatformRightUrl != null){
                            $("#logo-2 img").attr("src", panelGraphic.PlatformRightUrl);
                        }else{
                            $("#logo-2 img").attr("src",'@Url.Content("~/Content/kafeteria/images/logo-2.png")');
                        }

                        $('#logo-1, #logo-2').show();
                    }
                    if (panelGraphic.PlatformLayoutType == 1){
                        $('#logo-1, #logo-2').hide();

                        if (panelGraphic.PlatformBannerUrl != null){
                            $('#banner-1 img').attr('src',panelGraphic.PlatformBannerUrl);
                            $('#banner-1').attr("style","width:500px; height:110px; margin:0 auto; overflow:hidden;");
                            $('#banner-1').show();
                        }
                    }

                    if (panelGraphic.PlatformLayoutType == 2){
                        if (panelGraphic.PlatformLeftUrl != null){
                            $("#logo-1 img").attr("src", panelGraphic.PlatformLeftUrl);
                        }else{
                            $("#logo-1 img").attr("src",'@Url.Content("~/Content/kafeteria/images/logo-1.png")');
                        }

                        if (panelGraphic.PlatformRightUrl != null){
                            $("#logo-2 img").attr("src", panelGraphic.PlatformRightUrl);
                        }else{
                            $("#logo-2 img").attr("src",'@Url.Content("~/Content/kafeteria/images/logo-2.png")');
                        }

                        if (panelGraphic.PlatformBannerUrl != null){
                            // Jak jest plik bannera to wyświetlamy go, usuwamy niepotrzebne margin, padding, dajemy floaty, środkujemy obrazki
                            $('#banner-1 img').attr('src',panelGraphic.PlatformBannerUrl);
                            
                            $('#banner-1').attr("style","width:500px; height:110px; margin:0 auto; float:left; padding:0; overflow:hidden;");
                            $('#logo-1, #logo-2').attr('style','padding:0; float:left ;width:230px; margin-top:0; height:110px; overflow:hidden;');
                            $('#logo-1 img, #logo-2 img').attr('style','display:block; margin-left:auto; margin-right:auto;');
                            $('#banner-1').show();
                        }
                        else{
                            /* Jak nie ma bannera to loga wyświetlamy po bokach */
                            $('#banner-1').hide();
                            $('#logo-1').css('float','left');
                            $('#logo-2').css('float','right');
                        }

                        $('#logo-1, #logo-2').show();
                    }
                }

                /* #9168 */
                var FreeSpaceUp = '10px';
                var FreeSpaceDown = '10px';
                if (panelGraphic.FreeSpaceUp != null && panelGraphic.FreeSpaceDown != null)
                {
                    FreeSpaceUp = panelGraphic.FreeSpaceUp;
                    FreeSpaceDown = panelGraphic.FreeSpaceDown;
                }

                $('#komunikaty').css({'margin-top': FreeSpaceUp, 'margin-bottom': FreeSpaceDown});

                }
                else
                {
                    var _backColor = 'FE9B00';
                    var _color = '371708';

                    $(".bg-color").css("background-color","#" + _backColor);
			        $(".kolor-btn.xbutton").css("background-color","#" + _backColor);

                    $(".bg-img").css("background-image","url('" + '@Url.Content("~/Content/kafeteria/images/bg/tlo-4.jpg")' + "')");

			        $(".color").css("color","#" + _color);
			        $("#top-menu ul li.color a").css("color","#" + _color);
			        $("#mainmenu ul li a").css("color","#" + _color);
			        $("#platformmenu ul li a").css("color","#" + _color);
			        $(".sub-menu ul li a").css("color","#" + _color);
			        $(".do-content h2").css("color","#" + _color);
			        $(".do-content h1").css("color","#" + _color);
			        $(".suma").css("color","#" + _color);
			        $(".cena-big").css("color","#" + _color);
			        $(".ui-tabs .ui-tabs-nav li a").css("color","#" + _color);
			        $("#logowanie-box h1").css("color","#" + _color);
                }

                 reloadChangePassowrdTabs();

}
        function refreshInfo(){
            $.post("/Kafeteria/" + lang + "/Home/SessionInfo", { }, function(data){
                if($("#IsSessionInfoHidden").val() == 'False'){
                    $("#komunikaty").html(data);
                }
                else{
                    var content = "<h2 class='color' style='font-family: Czcionka;'></h2>";
                    $("#komunikaty").html(content);
                }
                var panelGraphic = getPlatformGraphic(currentPlatformId);
                $("#komunikaty").children().css("color","#"+panelGraphic.ForegroundColor);
                $("#komunikaty h2").css('font-family',panelGraphic.Font);
				$("#komunikaty a").css('font-family',panelGraphic.Font);

                $("a.change-frequency").fancybox({
				    'width'				: 600,
				    'height'			: 270,
				    'overlayColor'      : '#fff',
				    'autoDimensions'    : false,
				    'autoScale'			: false,
				    'transitionIn'		: 'none',
				    'transitionOut'		: 'none',
				    'type'				: 'ajax'
			    });
            });
        }

        function post_to_url(path, params, method) {
            method = method || "post"; // Set method to post by default, if not specified.

            // The rest of this code assumes you are not using a library.
            // It can be made less wordy if you use one.
            var form = document.createElement("form");
            form.setAttribute("method", method);
            form.setAttribute("action", path);

            for(var key in params) {
                if(params.hasOwnProperty(key)) {
                    var hiddenField = document.createElement("input");
                    hiddenField.setAttribute("type", "hidden");
                    hiddenField.setAttribute("name", key);
                    hiddenField.setAttribute("value", params[key]);

                    form.appendChild(hiddenField);
                 }
            }

            document.body.appendChild(form);
            form.submit();
        }

    </script>
}
@section menu{
    <ul>
        @if (Model.StartSiteVisibility)
        {<li id="tab-start" class="first active"><a href="javascript:void(0)"><span>@Html._("Start")</span></a></li>}
        else
        { <script type="text/javascript">
              $(document).ready(function () {
                  $('#main-con .tab-container:eq(0)').hide().next("div[id^='content']").show();
              });
        </script>}
        @if (Model.OrderDescriptionVisibility)
        {
            if (Model.StartSiteVisibility)
            { 
            <text><li id="tab-zamowienia"><a href="javascript:void(0)"><span>@Model.OrderTitle</span></a></li></text>
            }
            else
            { 
            <text><li id="tab-zamowienia" class="first active"><a href="javascript:void(0)"><span>@Model.OrderTitle</span></a></li></text>
            }
        }
        @if (@Model.CardsDescriptionVisibility)
        { <li id="tab-karty"><a href="javascript:void(0)"><span>@Model.CardsTitle</span></a></li>}
        @if (@Model.PeriodServiceDescriptionVisibility)
        { <li id="tab-uslugi-okresowe"><a href="javascript:void(0)"><span>@Model.PeriodServiceTitle</span></a></li>}
        @if (@Model.VoucherDescriptionVisibility)
        { <li id="tab-bony"><a href="javascript:void(0)"><span>@Model.VoucherTitle</span></a></li>}
        @if (@Model.ServiceHistoryDescriptionVisibility)
        { <li id="tab-historia-zamowien"><a href="javascript:void(0)"><span>@Model.ServiceHistoryTitle</span></a></li>}
        @if (@Model.SmSCodesDescriptionVisibility)
        {<li id="tab-kody-sms" class="last"><a href="javascript:void(0)"><span>@Model.SmsCodesTitle</span></a></li> }
        @if (@Model.PaymentDescriptionVisibility)
        {<li id="tab-platnosci" class="last"><a href="javascript:void(0)"><span>@Model.PaymentTitle</span></a></li> }
    </ul>
}
<script type="text/javascript">
    $(document).ready(function () {
        ReloadPlatformGUI(platformGraphicList[0]);
       
    });
</script>
<div id="content-start" class="tab-container">
    <div id="top-jedna-platforma">
    </div>
    @Html.Partial("Partials/_StartSite", Model)
</div>
@if (Model.OrderDescriptionVisibility)
{ 
    <div id="content-zamowienia" class="tab-container" style="display: none;">
        @Html.Partial("Partials/_Orders", Model)
    </div>
}
@if (@Model.CardsDescriptionVisibility)
{ 
    <div id="content-karty" class="tab-container" style="display: none;">
        @Html.Action("MultisportCards")
    </div>
}
@if (@Model.PeriodServiceDescriptionVisibility)
{ 
    <div id="content-uslugi-okresowe" class="tab-container" style="display: none;">
        @Html.Action("PeriodServices")
    </div>

}
@if (@Model.VoucherDescriptionVisibility)
{ 
    <div id="content-bony" class="tab-container" style="display: none;">
        @Html.Action("Bones")
    </div>
}
@if (@Model.ServiceHistoryDescriptionVisibility)
{ 
    <div id="content-historia-zamowien" class="tab-container">
        @*@Html.Action("Reports")*@
    </div>
}
@if (@Model.SmSCodesDescriptionVisibility)
{ 
    <div id="content-kody-sms" class="tab-container" style="display: none;">
        @Html.Action("SMSCodes", new { @Model.SmsCodesShortDescription })
        <div id="SmsInfo" style="display: none;">
        </div>
    </div>
}
@if (@Model.PaymentDescriptionVisibility)
{ 
    <div id="content-platnosci" class="tab-container" style="display: none;">
        @Html.Action("Payments", new { @Model.PaymentShortDescription })
        <div id="platnosci" style="display: none;">
        </div>
    </div>
}
<div id="loading">
    <div id="loadingcontent">
        <p id="loadingspinner">
            @Html._("Proszę czekać")
        </p>
    </div>
</div>

<div id="SendEmailDialog" title="Pobieranie kodu na e-mail" style="display:none">
    <br />
    <br />
    <br />
    <br />
    @Html.Label(@Html._("Proszę wybrać e-mail, na który zostanie wysłany kod:")) <br /> <br />
    @Html.RadioButton("TypEmaila", "0", true) @Html._("Służbowy") <br />
    @Html.RadioButton("TypEmaila","1", false) @Html._("Prywatny")
    
</div>

<script type="text/javascript">
    function DownloadCode(id) {
        //if (confirm('@Html._("Czy na pewno chcesz pobrać kod SMS ?")')) {
            $.post('@Url.Action("_DownloadCode")', { 'SmsCodeId': id }, function (data) {

                $("#content-kody-sms").load('@Url.Action("SMSCodes", new { @Model.SmsCodesShortDescription })');
                var panelGraphic = getPlatformGraphic(currentPlatformId);
                ReloadPlatformGUI(panelGraphic);

                ShowInformationBox();
            });
        //}
    }
    function PrintCode(id, Downloaded) {
        //var message = '@Html._("Czy na pewno chcesz wydrukować kod SMS ?")';
        //        if (!Downloaded) to już nie aktualne
        //            message += '@Html._("Operacji nie da się cofnąć.")';
        //        
        //if (confirm(message)) {
            setTimeout(LoadSMSCodes, 1000);
            if ($.browser.msie) { /* Padajce na kolana przed Internet Explorerem niegodziwi programiści albowiem wielka kapryśność jego może was stłamsić !! */
                window.open('@Url.Action("_SMSCodesPrint")' + '?SmsCodeId=' + id, null, "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
                //window.open('@Url.Action("_SMSCodesPrint")' + '?SmsCodeId=' + id, '_blank', '', '');
            } else {
                window.open('@Url.Action("_SMSCodesPrint")' + '?SmsCodeId=' + id, 'Wydruk kodu', '', '');
            }

            //window.print();
        //}
    }

    function EmailCode(id) {

        $.post('@Url.Action("CheckEmailAdress")', { 'SmsCodeId': id }, function (data) {
            // option = 0 - uż nie posiada żadnego adresu email
            // option = 2 - uż posiada dwa adresy email
            // option = 1 - uż posiada dokładnie jeden adres email
            if (data.option == "0") {
                SetInformationBox(1, '@Html._("Nie udało się pobrać kodu. Użytkownik nie posiada zdefiniowanego adresu e-mail.")');
                ShowInformationBox();
            }
            else if (data.option == "1") {
            }
            else if (data.option == "2") {

                jConfirm($("#SendEmailDialog").html().toString().replace(/\n/g, ''), "Pobieranie kodu na e-mail",
                    function (ret) {
                        if (ret) {
                            // 0 - służbowy e-mail
                            var email = "";
                            if ($("#TypEmaila").val() == "0") {
                                email = data.email;
                            }
                            // 1 - prywatny e-mail
                            else if ($("#TypEmaila").val() == "1") {
                                email = data.pivateEmail;
                            }
                            $.post('@Url.Action("_EmailCode")', { 'SmsCodeId': id, 'EmailAdress': email }, function (data) {
                                ShowInformationBox();
                                $("#content-kody-sms").load('@Url.Action("SMSCodes", new { @Model.SmsCodesShortDescription })');
                                var panelGraphic = getPlatformGraphic(currentPlatformId);
                                ReloadPlatformGUI(panelGraphic);
                            });
                        }
                    });
            }

        });

//    $.post('@Url.Action("_EmailCode")', { 'SmsCodeId': id }, function (data) {

//        $("#content-kody-sms").load('@Url.Action("SMSCodes", new { @Model.SmsCodesShortDescription })');
//        var panelGraphic = getPlatformGraphic(currentPlatformId);
//        ReloadPlatformGUI(panelGraphic);

//        ShowInformationBox();
//    });



//    $("#SendEmailDialog").dialog({ buttons: {
//        "OK": function () {
//            $(this).dialog("close");
//        },
//        "Anuluj": function () {
//            $(this).dialog("close");
//        }
//    }
//});

       
    }

    function LoadSMSCodes() {
        $("#content-kody-sms").load('@Url.Action("SMSCodes", new { @Model.SmsCodesShortDescription })');
    }
    $("#employee-declare-source-finance").click(function () {
        $.post('@Url.Action("EmployeeDeclareSourceFinance")', {}, function () {

        });
    })
</script>
<a class="employee-declare-source-finance" href=""></a>
@if (Model.ChangePasswordPopup)
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('a[rel="#passwordBox"]').trigger('click');
            $('#cp_close').hide();
        });
        $(document).keydown(function (e) {
            if (e.keyCode == 27) return false;
        });
    </script>
}


